//
//  QRViewController.m
//  QinWuBing
//
//  Created by 刘宇 on 16/4/15.
//  Copyright © 2016年 BangNiWuLian. All rights reserved.
//

#import "QRViewController.h"

@interface QRViewController ()<UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property ( strong , nonatomic ) AVCaptureDevice * device;
@property ( strong , nonatomic ) AVCaptureDeviceInput * input;
@property ( strong , nonatomic ) AVCaptureMetadataOutput * output;
@property ( strong , nonatomic ) AVCaptureSession * session;
@property ( strong , nonatomic ) AVCaptureVideoPreviewLayer * preview;

@property (strong , nonatomic) UIView  *centerView;  /*中间的扫描区域 方框*/
@end

@implementation QRViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self startScan];
    
    [self steupUI];
    [self startScan];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.session stopRunning];
    
}
- (void)steupUI{
    _centerView = [[UIView alloc]init];
    _centerView.bounds = CGRectMake(0, 0, SIZE(480), SIZE(480));
    _centerView.center = CGPointMake(WIDTH/2.0, HEIGHT/2.0-SIZE(200));
    [self.view addSubview:_centerView];
    
    UIImageView *centerBg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _centerView.frame.size.width, _centerView.frame.size.height)];
    centerBg.image = [UIImage imageNamed:@"accept_scan_bg"];
    [_centerView addSubview:centerBg];
    
    UIButton    *back = [[UIButton alloc]initWithFrame:CGRectMake(20, 50, SIZE(72), SIZE(72))];
    [back setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:back];
    
    UIView  *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, _centerView.frame.origin.y)];
    topView.backgroundColor = [UIColor colorWithRed:0.04 green:0.02 blue:0.01 alpha:0.6];
    [self.view addSubview:topView];
    UIView  *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, topView.frame.size.height, _centerView.frame.origin.x, _centerView.frame.size.height)];
    leftView.backgroundColor = [UIColor colorWithRed:0.04 green:0.02 blue:0.01 alpha:0.6];
    [self.view addSubview:leftView];
    UIView  *rightView = [[UIView alloc]initWithFrame:CGRectMake(WIDTH-leftView.frame.size.width, leftView.frame.origin.y, leftView.frame.size.width, leftView.frame.size.height)];
    rightView.backgroundColor = [UIColor colorWithRed:0.04 green:0.02 blue:0.01 alpha:0.6];
    [self.view addSubview:rightView];
    UIView  *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _centerView.frame.origin.y+_centerView.frame.size.height, WIDTH, HEIGHT-(_centerView.frame.origin.y+_centerView.frame.size.height))];
    bottomView.backgroundColor = [UIColor colorWithRed:0.04 green:0.02 blue:0.01 alpha:0.6];
    [self.view addSubview:bottomView];
    
    UILabel *noteLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, WIDTH, SIZE(80))];
    noteLable.text = @"扫描二维码进行签到";
    noteLable.textColor = [UIColor whiteColor];
    noteLable.textAlignment = NSTextAlignmentCenter;
    [bottomView addSubview:noteLable];
    
    UIButton    *myQRBtn = [[UIButton alloc]initWithFrame:CGRectMake(50, noteLable.frame.origin.y+noteLable.frame.size.height+10, WIDTH-50*2, SIZE(80))];
    [myQRBtn setTitle:@"我的二维码" forState:UIControlStateNormal];
    [myQRBtn setTitleColor:[UIColor colorWithRed:0.08 green:0.67 blue:0.05 alpha:1] forState:UIControlStateNormal];
    [bottomView addSubview:myQRBtn];

    UIImageView *scanLine = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _centerView.frame.size.width, 2)];
    scanLine.image = [UIImage imageNamed:@"accept_scanLine"];
    [_centerView addSubview:scanLine];
    [scanLine sendSubviewToBack:_centerView];
    
    [UIView  beginAnimations:@"scan" context:(__bridge void * _Nullable)(scanLine)];
    [UIView setAnimationRepeatCount:MAXFLOAT];
    [UIView setAnimationDuration:1];
    [UIView setAnimationRepeatAutoreverses:YES];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    scanLine.frame = CGRectMake(0, _centerView.frame.size.height, _centerView.frame.size.width, 2);
//    [UIView setAnimationDidStopSelector:@selector(scanAnimation:)];
    [UIView commitAnimations];
    
}
- (void)scanAnimation:(nullable void *)context{
    UIImageView *scanLine = (__bridge UIImageView *)(context);
    scanLine.frame = CGRectMake(0, 0, _centerView.frame.size.width, 2);
}
- (void)startScan
{

    // Device
    _device = [ AVCaptureDevice defaultDeviceWithMediaType : AVMediaTypeVideo ];
    // Input
    _input = [ AVCaptureDeviceInput deviceInputWithDevice : self . device error : nil ];
    // Output
    _output = [[ AVCaptureMetadataOutput alloc ] init ];
    [ _output setMetadataObjectsDelegate : self queue : dispatch_get_main_queue ()];
    // Session
    _session = [[ AVCaptureSession alloc ] init ];
    [ _session setSessionPreset : AVCaptureSessionPresetHigh ];
    if ([ _session canAddInput : self . input ])
    {
        [ _session addInput : self . input ];
    }
    if ([ _session canAddOutput : self . output ])
    {
        [ _session addOutput : self . output ];
    }
    // 条码类型 AVMetadataObjectTypeQRCode
    _output . metadataObjectTypes = @[ AVMetadataObjectTypeQRCode ] ;
    // Preview
    _preview =[ AVCaptureVideoPreviewLayer layerWithSession : _session ];
    _preview . videoGravity = AVLayerVideoGravityResizeAspectFill ;
    _preview . frame = self . view . layer . bounds ;
    [ self . view . layer insertSublayer : _preview atIndex : 0 ];
    // Start
    [ _session startRunning ];
    [self.session startRunning];
}
#pragma mark --------AVCaptureMetadataOutputObjectsDelegate ---------
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    if ([metadataObjects count ] > 0 )
    {
        // 停止扫描
        [ _session stopRunning ];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        stringValue = metadataObject.stringValue ;
        NSLog(@"扫描结果 %@",stringValue);
    }
}
//- (void)
- (void)back{
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
